<?php

class DBConnection
{
	function DBConnection()
	{
		static $conn_id;

		if (is_resource($conn_id))
		{
			$this->id_ = $conn_id;
			return;
		}
		if(defined('DB_PORT'))
		{
			if (!$this->id_ = mysql_connect(DB_HOST.':'.DB_PORT, DB_USER, DB_PASS))
				die("Unable to connect to mysql database.");
		}
		else
		{
			if (!$this->id_ = mysql_connect(DB_HOST, DB_USER, DB_PASS))
				die("Unable to connect to mysql database.");
		}
		mysql_select_db(DB_NAME);
		$conn_id = $this->id_;
	}

	function id()
	{
		return $this->id_;
	}

	function affectedRows()
	{
		return mysql_affected_rows($this->id_);
	}
}


//! mysql uncached query class. Manages SQL queries to a MySQL DB using mysql.
class DBQuery
{
//! Prepare a connection for a new mysql query.
	function DBQuery()
	{
		static $totalexectime = 0;
		$this->totalexectime_ = &$totalexectime;
		$this->executed_ = false;
		$this->dbconn_ = new DBConnection;
	}

	// Return the count of queries performed.
	function queryCount($increase = false)
	{
		static $count;

		if ($increase)
		{
			$count++;
		}

		return $count;
	}

	
	// Execute an SQL string.
	function execute($sql)
	{
		$t1 = strtok(microtime(), ' ') + strtok('');

		$this->resid_ = mysql_query($sql, $this->dbconn_->id());
		if (!$this->resid_ || mysql_errno($this->dbconn_->id()))
		{

			return false;
		}

		$this->exectime_ = strtok(microtime(), ' ') + strtok('') - $t1;
		$this->totalexectime_ += $this->exectime_;
		$this->executed_ = true;

		$this->queryCount(true);

		return true;
	}

	// Return the number of rows returned by the last query.
	function recordCount()
	{
		return mysql_num_rows($this->resid_);
	}

	// Return the next row of results from the last query.
	function getRow()
	{
		if ($this->resid_)
		{
			return mysql_fetch_assoc($this->resid_);
		}
		return false;
	}

	//! Reset list of results to return the first row from the last query.
	function rewind()
	{
		@mysql_data_seek($this->resid_, 0);
	}

	//! Return the auto-increment ID from the last insert operation.
	function getInsertID()
	{
		return mysql_insert_id();
	}

	//! Return the execution time of the last query.
	function execTime()
	{
		return $this->exectime_;
	}

	//! Return true if a query has been executed or false if none has been.
	function executed()
	{
		return $this->executed_;
	}

	//! Return the most recent error message for the DB connection.
	function getErrorMsg()
	{
		$msg = $this->sql_ . "<br>";
		$msg .= "Query failed. " . mysql_error($this->dbconn_->id());

		return $msg;
	}
}

?>